package com.soilflow.web.controller.reception.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.core.domain.entity.SysUser;
import com.soilflow.common.domain.vo.BindPhoneVo;
import com.soilflow.framework.web.service.SysLoginService;
import com.soilflow.framework.web.service.TokenService;
import com.soilflow.info.service.MessageService;
import com.soilflow.system.service.ISysUserService;
import com.soilflow.web.utils.HttpClientUtils;
import io.jsonwebtoken.JwtHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/admin/wechat")
@CrossOrigin
@Slf4j
public class WechatController {

    @Autowired
    private ISysUserService  userService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;
    @Value("${wechat.mpAppId}")
    private String mpAppId;
    @Value("${wechat.mpAppSecret}")
    private String mpAppSecret;

    /**
     * 第一步，同意授权，获取code
     * @return
     */
    @GetMapping("/wxLogin")
    public String wxLogin() throws IOException {
        System.out.println("mpAppId = " + mpAppId);
        System.out.println("userInfoUrl = " + userInfoUrl);
        //String url =
        //        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +mpAppId +
        //                "&redirect_uri=" + URLEncoder.encode(userInfoUrl) +
        //                "&response_type=code" +
        //                "&scope=snsapi_base" +
        //                "&state=1#wechat_redirect";
        String url =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +mpAppId +
                        "&redirect_uri=" + userInfoUrl +
                        "&response_type=code" +
                        "&scope=snsapi_userinfo" +
                        "&state=STATE#wechat_redirect";
        //JSONObject jsonObject = HttpClientUtils.doGet(url);
        //String code = jsonObject.getString("code");
        return "redirect:" + url;
    }


    //@ResponseBody
    @GetMapping("/userInfo")
    public String userInfo( @RequestParam("code")String code) throws Exception {
        System.out.println("============");
        System.out.println("code = " + code);
        // 第二步，通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + mpAppId+
                "&secret=" + mpAppSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject jsonObject = HttpClientUtils.doGet(url);
        String openid = jsonObject.getString("openid");
        System.out.println("openid = " + openid);
        String access_token = jsonObject.getString("access_token");
        // 获取openid判断用户是否登录过系统

        SysUser sysUser = sysUserService.getOne( openid);
        System.out.println("sysUser = " + sysUser);
        String token = "";
        token = sysLoginService.login("成诗华"+"_Duocai", "admin123", null, null);

        System.out.println("token = " + token);
        return "redirect:" + "http://192.168.2.86/index2" + "?token=" + token + "&openId=" + openid;
        //return token;
    }




//    @PostMapping("bindPhone")
//    @ResponseBody
//    public AjaxResult bindPhone(@RequestBody BindPhoneVo bindPhoneVo) {
//        SysUser sysUser = userService.selectByphone(bindPhoneVo.getPhonenumber());
//        if(null != sysUser) {
//            sysUser.setOpenid(bindPhoneVo.getOpenId());
//            userService.updateById(sysUser);
//
////            String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
//            return AjaxResult.success(token);
//        } else {
//            return AjaxResult.error("手机号码不存在，绑定失败");
//        }
//    }
        @GetMapping("/send")
        public AjaxResult send() throws Exception {
            messageService.pushPendingMessage(Long.valueOf(1));
            return AjaxResult.success("发送成功");
        }
}
